<template>
	<div class="app-container calendar-list-container">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-top: 5px; margin-bottom: 25px; margin-left: 10px;">
            <el-breadcrumb-item v-for="(item, index) in breadList"><a href="javascript:;" @click="pushBread(item, index)">{{item.regionName}}</a></el-breadcrumb-item>
            <el-breadcrumb-item>成员列表</el-breadcrumb-item>
        </el-breadcrumb>
		<div class="filter-container">
			<!--搜索条件-->
			<el-form :inline="true" :model="screen" class="demo-form-inline" v-if="region.level != 3">
				<el-form-item>
					<el-select v-model="screen.type" placeholder="请选择">
						<el-option label="代理商" value="1"></el-option>
						<el-option label="导购员" value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-input v-model="screen.keyword" placeholder="请输入名称关键词"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit">
						<i class="el-icon-search"></i> 查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="regionNew()" v-if="(region.level == 0 || region.level == 1) && screenUser === false">
						<i class="el-icon-plus"></i> 新增区域</el-button>
					<el-button type="primary" @click="storeNew()" v-if="region.level == 2 && screenUser === false">
						<i class="el-icon-plus"></i> 新增门店</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!--数据列表-->
		<el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" stripe style="width: 100%">
			<el-table-column width="180" v-for="item in tableHead" :prop="item.key" :label="item.value" >
			</el-table-column>
			<el-table-column label="操作" min-width="400">
				<template slot-scope="scope">
					<el-button size="mini" plain @click="nextRegion(scope.row)" v-if="region.level == 0 && screenUser === false">查看二级</el-button>
					<el-button size="mini" plain @click="nextRegion(scope.row)" v-else-if="region.level == 1 && screenUser === false">查看门店</el-button>
					<el-button size="mini" plain @click="nextRegion(scope.row)" v-else-if="region.level == 2 && screenUser === false">查看导购</el-button>

					<el-button size="mini" plain type="primary" icon="el-icon-edit" v-if="region.level == 3 || screenUser === true" @click="userEdit(scope.row)">编辑</el-button>
					<el-button size="mini" plain type="primary" icon="el-icon-edit" v-else-if="region.level == 2" @click="storeEdit(scope.row)">编辑</el-button>
					<el-button size="mini" plain type="primary" icon="el-icon-edit" v-else @click="regionEdit(scope.row)">编辑</el-button>

					<el-button size="mini" plain type="warning" icon="el-icon-refresh" @click="reset(scope.row.id)">重置密码</el-button>
					<el-button size="mini" plain type="danger" icon="el-icon-delete" v-if="region.level == 2 || region.level == 3 || screenUser === true"
					    @click="regionDelete(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container" style="text-align: center; margin-top: 30px;">
			<el-pagination :current-page="page.offset" :total="page.total" layout="prev, pager, next" @current-change="handleCurrentChange">
			</el-pagination>
		</div>

		<!-- 区域弹窗 -->
		<el-dialog :title="dialog1.EditText" :visible.sync="dialog1.Visible">
			<el-form :model="dialog1.form" :rules="dialog1.rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" status-icon>
				<el-form-item label="所属上级">
					<span>{{region.regionName}}</span>
				</el-form-item>
				<el-form-item label="完整名称" prop="region">
					<el-input v-model="dialog1.form.region" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="简称" prop="simpleReg">
					<el-input v-model="dialog1.form.simpleReg" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="区域编码" prop="regCode">
					<el-input v-model="dialog1.form.regCode" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="负责人账号" prop="account">
					<el-input v-model="dialog1.form.account" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="负责人密码" v-if="dialog1.EditId == ''" prop="password">
					<el-input v-model="dialog1.form.password" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialog1.Visible = false">取 消</el-button>
				<el-button type="primary" v-if="dialog1.EditId == ''" @click="saveDialogMember('ruleForm')">确 定</el-button>
				<el-button type="primary" v-else @click="eidtDialogMember('ruleForm')">确 定</el-button>
			</div>
		</el-dialog>

        <!-- 门店弹窗 -->
		<el-dialog :title="dialog2.EditText" :visible.sync="dialog2.Visible">
			<el-form :model="dialog2.form" :rules="dialog2.rules" ref="ruleForm2" label-width="100px" class="demo-ruleForm" status-icon>
				<el-form-item label="所属区域">
					<span>{{region.regionName}}</span>
				</el-form-item>
				<el-form-item label="门店名称" prop="region">
					<el-input v-model="dialog2.form.store" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="门店简称" prop="simpleReg">
					<el-input v-model="dialog2.form.simpleStore" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialog2.Visible = false">取 消</el-button>
				<el-button type="primary" v-if="dialog2.EditId == ''" @click="saveDialogStore('ruleForm2')">确 定</el-button>
				<el-button type="primary" v-else @click="editDialogStore('ruleForm2')">确 定</el-button>
			</div>
		</el-dialog>

        <!-- 编辑导购弹窗 -->
		<el-dialog title="编辑导购" :visible.sync="dialog3.Visible">
			<el-form :model="dialog3.form" :rules="dialog3.rules" ref="ruleForm3" label-width="100px" class="demo-ruleForm" status-icon>
				<el-form-item label="所属区域">
					<span>{{region.regionName}}</span>
				</el-form-item>
				<el-form-item label="姓名" prop="region">
					<el-input v-model="dialog3.form.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="simpleReg">
					<el-input v-model="dialog3.form.mobile" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="simpleReg">
					<el-select v-model="dialog3.form.status" placeholder="请选择">
						<el-option label="在职" value="1"></el-option>
						<el-option label="离职" value="0"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialog3.Visible = false">取 消</el-button>
				<el-button type="primary" @click="editDialogUser('ruleForm3')">确 定</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
	const RULES = {
		region: [{
			required: true,
			message: '请输入完整名称',
			trigger: 'blur'
		}, {
			min: 1,
			max: 10,
			message: '长度在 1 到 10 个字符',
			trigger: 'blur'
		}]
	}
	const RULES2 = {
		store: [{
			required: true,
			message: '请输入完整名称',
			trigger: 'blur'
		}, {
			min: 1,
			max: 10,
			message: '长度在 1 到 10 个字符',
			trigger: 'blur'
		}]
	}
	const RULES3 = {
		username: [{
			required: true,
			message: '请输入完整名称',
			trigger: 'blur'
		}, {
			min: 1,
			max: 10,
			message: '长度在 1 到 10 个字符',
			trigger: 'blur'
		}]
	}

	export default {
		name: 'complexTable',
		data() {
			return {
                listLoading: true,
                breadList: [], //面包屑
                dialog1: {
                    Visible: false,
                    form: {},
                    rules: RULES,
                    EditId: '', //编辑窗口Id
                    EditText: '',
                },
                dialog2: {
                    Visible: false,
                    form: {},
                    rules: RULES2,
                    EditId: '', //编辑窗口Id
                    EditText: '',
                },
                dialog3: {
                    Visible: false,
                    form: {},
                    rules: RULES3
                },
				screen: { //筛选条件
					type: '1',
					keyword: ''
				},
				screenUser: false, // ture: 筛选条件为导购
				page: {
					pageSize: 10,
					offset: 1,
					total: null
				},
				region: { //区域信息
					regionId: '',
					regionName: '',
					level: ''
				},
				list: null
			}
		},
		computed: {
			tableHead() {
				const HEAD1 = [{
					value: '区域名称',
					key: 'region'
				}, {
					value: '区域简称',
					key: 'simpleReg'
				}, {
					value: '区域编码',
					key: 'regCode'
				}, {
					value: '负责人账号',
					key: 'account'
				}, {
					value: '导购数量',
					key: 'total'
				}]

				const HEAD2 = [{
					value: '门店名称',
					key: 'region'
				}, {
					value: '门店简称',
					key: 'simpleReg'
				}, {
					value: '导购数量',
					key: 'total'
				}]

				const HEAD3 = [{
					value: '导购姓名',
					key: 'username'
				}, {
					value: '导购码',
					key: 'number'
				}, {
					value: '手机号',
					key: 'mobile'
				}, {
					value: '状态',
					key: 'status'
				}, ]

				if (this.region.level === 3 || this.screenUser === true) { //如果为导购
					return HEAD3
				} else if (this.region.level === 2) {
					return HEAD2
				} else {
					return HEAD1
				}

			}
		},
		methods: {
			onSubmit() {
				this.page.offset = 1
				this.fetchData().then(() => {
					if (this.screen.type == 2) {
						this.screenUser = true
					} else {
						this.screenUser = false
					}
				})
			},
			handleCurrentChange(val) {
				this.page.offset = val
				this.fetchData()
			},
			regionNew() { //新增区域窗口
				this.dialog1.EditId = '' //清空编辑判断条件
				this.dialog1.form = {
                    region: '',
					simpleReg: '',
					regCode: '',
					account: '',
					password: ''
				}
				this.dialog1.EditText = '新增区域'
				this.dialog1.Visible = true
			},
			regionEdit(scope) { //编辑区域窗口
				this.dialog1.form = {
					region: scope.region,
					simpleReg: scope.simpleReg,
					regCode: scope.regCode,
					account: scope.account,
					password: scope.password
				}
				this.dialog1.EditId = scope.id
				this.dialog1.EditText = '编辑区域'
				this.dialog1.Visible = true
			},
			saveDialogMember(formName) { //保存新增区域
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const data = Object.assign({}, this.dialog1.form, {
							parentId: this.region.regionId,
							parentRegion: this.region.regionName,
							level: parseInt(this.region.level) + 1 // 下级区域
                        })
                        const url = '/reservephone/admin/Region/saveRegion.json'
                        this.saveMember(url, data).then((res) => {
							this.dialog1.Visible = false
							this.fetchData()
							this.$notify({
								title: '成功',
								message: '保存成功',
								type: 'success',
								duration: 2000
							})
                        })
					}
				})
			},
			eidtDialogMember(formName) { //保存编辑区域
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const data = Object.assign({}, this.dialog1.form, {
							regionId: this.dialog1.EditId
                        })
                        const url = '/reservephone/admin/Region/saveRegion.json'
                        this.saveMember(url, data).then(() => {
							this.dialog1.Visible = false
							this.fetchData()
							this.$notify({
								title: '成功',
								message: '修改成功',
								type: 'success',
								duration: 2000
							})
                        })
					}
				})
            },
            storeNew() { //新增门店窗口
				this.dialog2.EditId = '' //清空编辑判断条件
				this.dialog2.form = {
                    store: '',
		            simpleStore: ''
				}
				this.dialog2.EditText = '新增门店'
				this.dialog2.Visible = true
			},
			storeEdit(scope) { //编辑门店窗口
				this.dialog2.form = {
					store: scope.region,
					simpleStore: scope.simpleReg
				}
				this.dialog2.EditId = scope.id
				this.dialog2.EditText = '编辑门店'
				this.dialog2.Visible = true
            },
            saveDialogStore(formName) { //保存新增门店
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const data = Object.assign({}, this.dialog2.form, {
							secondRegionId: this.region.regionId
                        })
                        const url = '/reservephone/admin/Region/saveStore.json'
                        this.saveMember(url, data).then((res) => {
							this.dialog2.Visible = false
							this.fetchData()
							this.$notify({
								title: '成功',
								message: '保存成功',
								type: 'success',
								duration: 2000
							})
                        })
					}
				})
			},
			editDialogStore(formName) { //保存编辑门店
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const data = Object.assign({}, this.dialog2.form, {
							storeId: this.dialog2.EditId
                        })
                        const url = '/reservephone/admin/Region/saveStore.json'
                        this.saveMember(url, data).then(() => {
							this.dialog2.Visible = false
							this.fetchData()
							this.$notify({
								title: '成功',
								message: '修改成功',
								type: 'success',
								duration: 2000
							})
                        })
					}
				})
            },
            userEdit(scope) {  // 编辑导购窗口
                this.dialog3.form = {
					username: scope.username,
					mobile: scope.mobile,
                    status: ""+ scope.status,
                    id: scope.id
				}
				this.dialog3.Visible = true
            },
            editDialogUser(formName) { //保存编辑导购
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const data = this.dialog3.form
                        const url = '/reservephone/admin/Region/updateGuide.json'
                        this.saveMember(url, data).then(() => {
							this.dialog3.Visible = false
							this.fetchData()
							this.$notify({
								title: '成功',
								message: '修改成功',
								type: 'success',
								duration: 2000
							})
                        })
					}
				})
            },
			saveMember(url, data) { // 新增/编辑区域接口
				return new Promise((resolve, reject) => {
					this.$axios({
						url: url,
						method: 'post',
						data: this.$qs.stringify(data)
					}).then((res) => {
						if (res.status === true || res.status === 'true') {
							resolve(res)
						}
					})
				})
			},
			reset(id) { //重置密码窗口
				this.$confirm('确认重置密码为初始密码？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.resetConfirm(id)
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消操作'
					});
				});

			},
			resetConfirm(id) { //确认重置
				const data = {
					regionId: id
				}
				this.listLoading = true
				this.$axios({
					url: '/reservephone/admin/Region/resetPwd.json',
					method: 'post',
					data: this.$qs.stringify(data)
				}).then((res) => {
                    this.listLoading = false
                    if (res.status === true || res.status === 'true') {
                        this.fetchData()
                        this.$notify({
                            title: '成功',
                            message: '密码重置成功',
                            type: 'success',
                            duration: 2000
                        })
                    }
				}).catch(() => {
					this.listLoading = false
				})
			},
			regionDelete(id) { //删除区域
				this.$confirm('确认删除操作？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.regionDeleteConfirm(id)
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消操作'
					})
				})
			},
            regionDeleteConfirm(id) { //确认删除
                // 如果为删除区域
                let data = {
                    storeId: id
                }
                let url = '/reservephone/admin/Region/deleteStore.json'

                if (this.region.level == 3 || this.screenUser === true) { // 如果为删除导购
                    url = '/reservephone/admin/Region/deleteGuide.json'
                    data = {
                        id: id
                    }
                }
				this.listLoading = true
				this.$axios({
					url: url,
					method: 'post',
					data: this.$qs.stringify(data)
				}).then((res) => {
                    this.listLoading = false
                    if (res.status === true || res.status === 'true') {
                        this.fetchData()
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
                    }
				}).catch(() => {
					this.listLoading = false
				})
            },
            pushBread(region, index) {
                this.breadList = this.breadList.slice(0, index+1)
                this.region = region
                this.screen = {
					type: '1',
					keyword: ''
                }
                this.screenUser = false
                this.page.offset = 1
                this.fetchData()
            },
			nextRegion(scope) { //查看二级区域
				this.region = {
					regionId: scope.id,
					regionName: scope.region,
					level: scope.level
				}
				this.screen = {
					type: '1',
					keyword: ''
                }
                this.screenUser = false
                this.page.offset = 1
				this.fetchData().then(() => {
                    this.breadList.push(this.region)
                })
			},
			fetchData(option) { // 请求表格数据接口
				return new Promise((resolve, reject) => {
					let page = {
						offset: this.page.offset,
						pageSize: this.page.pageSize
					}
					let region = {
						regionId: this.region.regionId,
						level: this.region.level
					}
					let data = Object.assign({}, page, region, this.screen)
					if (typeof option === 'object') {
						data = Object.assign({}, data, option)
					}
					this.listLoading = true
					this.$axios({
						url: '/reservephone/admin/Region/index.json',
						method: 'post',
						data: this.$qs.stringify(data)
					}).then((res) => {
						this.listLoading = false
						if (res.status === true || res.status === 'true') {
							this.list = res.data.rows
							this.page.total = res.data.total
							resolve(res)
						}
					}).catch(() => {
						this.listLoading = false
						reject(err)
					})
				})
			},
			setRegion() {
				this.region = { //区域信息
					regionId: this.$store.state.user.info.id,
					regionName: this.$store.state.user.info.region,
					level: this.$store.state.user.info.level
                }
                this.breadList[0] = this.region
			}
		},
		created() {
			this.setRegion()
			this.fetchData()
		}
	}

</script>
